//设置根地址
axios.defaults.baseURL='http://ajax-base-api-t.itheima.net'

const tbody=document.querySelector('#tb')
const form=document.querySelector('#bookForm')
//解决方案1：可以给新加的button按钮绑定type=button属性，这样就不会跟form的submit事件冲突
//解决方法2：还可以分开绑定两个点击事件(分开绑定都要阻止默认跳转)
//button按钮的type默认属性是submit
const btn2 = document.querySelector('.select')

const renderTable =async()=>{
  const obj = serialize(form, { hash: true })
  const {data:res} =await axios.get('/api/getbooks',{params:obj})
tbody.innerHTML=res.data.map((item) => {
    return `<tr>
    <td>${item.id}</td>
    <td>${item.bookname}</td>
    <td>${item.author}</td>
    <td>${item.publisher}</td>
    <td ><a href="#" data-id="${item.id}">删除</a></td>
    <tr>`
   }).join('')
}
renderTable()

//添加
form.addEventListener('submit', async function (e) {
  e.preventDefault()
  const obj = serialize(form, { hash: true })
  const { data: res } = await axios.post('/api/addbook', obj)
  alert(res.msg)
  form.reset()
  if (res.status !== 201) return
  renderTable()
})

//删除
tbody.addEventListener('click',async function (e) {
  if (e.target.tagName === 'A') {
    const id = e.target.dataset.id
    const {data:res}  =await axios.get('/api/delbook?id=' + id)
    alert(res.msg)
    if (res.status !== 200) return
    renderTable()
  }
})

//筛选
btn2.addEventListener('click', function (e) {
  renderTable()
})